<!--
 * @Descripttion: 
 * @version: 
 * @Author: kk
 * @Date: 2020-10-23 12:21:40
 * @LastEditors: kk
 * @LastEditTime: 2020-10-30 17:44:40
-->
<!--  -->
<template>
  <div>
    <!-- 查询用户 -->
    <div class="Center">
      <el-form
        :inline="true"
        :model="userQuery"
        class="demo-form-inline"
      >
        <el-form-item label="用户名称">
          <el-input
            v-model="userQuery.username"
            placeholder="username"
          ></el-input>
        </el-form-item>
        <el-form-item label="手机号码">
          <el-input
            v-model="userQuery.phone"
            placeholder="phone"
          ></el-input>
        </el-form-item>
          <el-form-item label="邮箱">
          <el-input
            v-model="userQuery.email"
            placeholder="email"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            @click="onSubmit"
          >查询</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div>
      
    <el-button type="primary" size="mini" class="btn_add" @click="openAddAdmin()">添加用户</el-button>

    <el-dialog :title="formName" :visible.sync="dialogFormVisible">
      <el-form :model="user">
        <el-form-item label="用户名" :label-width="formLabelWidth">
          <el-input v-model="user.userName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="密码" :label-width="formLabelWidth">
          <el-input v-model="user.password" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="联系方式" :label-width="formLabelWidth">
          <el-input v-model="user.phone" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="Email" :label-width="formLabelWidth">
          <el-input v-model="user.email" autocomplete="off"></el-input>
        </el-form-item>
  </el-form>
  <div slot="footer" class="dialog-footer">
    <el-button @click="dialogFormVisible = false">取 消</el-button>
    <el-button type="primary" @click="addOrUpdateAdmin()">提 交</el-button>
  </div>
</el-dialog>

    <el-table
      class="AdminTable"
      :data="admins"
      border
      style="width: 95%"
    >
      <el-table-column
        prop="id"
        label="ID"
      >
      </el-table-column>
      <el-table-column
        prop="userName"
        label="用户名称"
      >
      </el-table-column>
      <el-table-column
        prop="phone"
        label="手机号码"
      >
      </el-table-column>
      <el-table-column
        prop="email"
        label="邮箱"
      >
      </el-table-column>
      <el-table-column
        prop="roleName"
        label="角色名"
      >
      <template slot-scope="scope" >
        <el-select v-model="scope.row.roleName" placeholder="请选择"
        @change="updateRole($event,scope.row.id)">
          <el-option
            v-for="role in roles"
            :key="role.value"
            :label="role.label"
            :value="role.value"
          >
          </el-option>
        </el-select>
      </template>
      </el-table-column>
      <el-table-column label="是否有效">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.isHidden"
            :active-value=1
            :inactive-value="0"
            active-color="#13ce66"
            inactive-color="#ff4949"
            @change="isHidden(scope.$index,scope.row)"
          >
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
      >
        <template slot-scope="scope">
            <el-button
            class="btn_update"
              type="primary"
              size="mini"
              icon="el-icon-edit"
              style="margin-right: 20px;"
              @click="openUpdateAdmin(scope.row.id)"
            >编辑用户</el-button>
          <el-button
          class="btn_update"
            type="danger"
            size="mini"
            icon="el-icon-delete"
            @click="openDeleteAdmin(scope.row.id)"
          >删除用户</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="block">
      <!-- 分页 -->
      <el-pagination
        :current-page="page"
        :page-size="limit"
        :total="total"
        style="padding: 30px 0; text-align: center;"
        layout="total, prev, pager, next, jumper"
        @current-change="getAdminList"
      />
    </div>
    </div>
  </div>
</template>

<script>
//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》';
import admin from "@/api/admin";
import role from "@/api/role";
import router from "@/router";

export default {
  //import引入的组件需要注入到对象中才能使用
  components: {},

  data() {
    return {
      admins: [],
      roles: [],
      page: 1,
      total: 100,
      limit: 10,
      value: '',
      userQuery: {},
      dialogFormVisible: false,
      user: {},
      formLabelWidth: '120px',
      formName: '添加用户'
    };
  },

  //监听属性 类似于data概念
  computed: {},
  //监控data中的数据变化
  watch: {},
  //方法集合
  methods: {
    openAddAdmin(){
      this.dialogFormVisible=true;
      this.formName='添加用户'
      this.user={}
    },
    addOrUpdateAdmin(){
      if(this.formName=='添加用户'){
        this.addAdmin();
      }else{
        this.updateAdmin();
      }
    },
    updateAdmin(){
      admin.updateAdmin(this.user).then(response=>{
        if(response.code==200){
          this.$message({
            type: "success",
            message: '更新成功',
          });
          this.getAdminList()
          this.dialogFormVisible=false
        }
      })
    },
    openUpdateAdmin(id){
      this.formName='更新用户';
      this.dialogFormVisible=true;
      this.getAdmin(id);
    },
    getAdmin(userId){
      admin.getAdmin(userId).then(response=>{
        this.user=response.data.user
      })
    },
    addAdmin(){
      admin.addAdmin(this.user).then(response=>{
        if(response.code==200){
          this.$message({
            type: "success",
            message: '添加成功',
          });
          this.getAdminList()
          this.dialogFormVisible=false
          this.user={}
        }
      })
    },
    updateRole(value,id){
      console.log(id) //用户id
      console.log(value) //角色id
      admin.assignRoleToAdmin(id,value).then(response=>{
          this.$message({
            type: "success",
            message: response.message,
          });
      })
      
    },
    getRoles() {
      role.getRoles().then((response) => {
        console.log(response.data)
        this.roles = response.data.roles;
      });
    },
    isHidden(index, row) {
      console.log(index, row);
      admin.updateStatus(row.id).then((response) => {});
    },
    //分页查询商品列表
    onSubmit() {
      this.getAdminList();
    },
    getAdminList(page = 1) {
      //默认为1
      this.page = page;
      admin.getAdminList(this.page, this.limit,this.userQuery).then((response) => {
        //请求成功
        console.log(response.data);
        const res = response.data;
        this.admins = res.admins;
        this.total = res.total;
      });
    },
    removeAdmin(id) {
      //console.log(id);
      admin.removeAdmin(id).then((response) => {
        if (response.code == 200) {
          this.$message({
            type: "success",
            message: "删除成功!",
          });
          //刷新
          this.getAdminList(this.page);
        }
      });
    },
    openDeleteAdmin(id) {
      this.$confirm("此操作将永久删除该用户, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.removeAdmin(id);
          this.$message({
            type: 'success',
            message: '删除成功！'
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    
    
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {
    this.getAdminList();
    this.getRoles();
  },
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {},
  beforeCreate() {}, //生命周期 - 创建之前
  beforeMount() {}, //生命周期 - 挂载之前
  beforeUpdate() {}, //生命周期 - 更新之前
  updated() {}, //生命周期 - 更新之后
  beforeDestroy() {}, //生命周期 - 销毁之前
  destroyed() {}, //生命周期 - 销毁完成
  activated() {}, //如果页面有keep-alive缓存功能，这个函数会触发
};
</script>
<style lang='scss' scoped>
//@import url(); 引入公共css类
.AdminTable {
  margin-left: 20px;
  margin-top: 20px;
}
.Center {
  // margin: 0 auto;
  // margin-top: 20px;
  padding: 30px 0;
  text-align: center;
  //align-content: center;
}
.btn_add{
  float: right;
  margin-right: 50px;
  margin-bottom: 20px;;
}
.btn_update{
  text-align: center;
  margin: 10px;
}
</style>